//
//  UIColor+ZRExtension.m
//  简书:https://www.jianshu.com/u/043e94ca450f
//
//  Created by 黄涛 on 2018/7/12.
//  Copyright © 2018年 zero. All rights reserved.
//

#import "UIColor+ZRExtension.h"

@implementation UIColor (ZRExtension)

#pragma mark - ----------------------- 颜色转换 -----------------------

/** 16 进制转 UIcolor 例:[#FFFFFF -> 白色] */
+ (UIColor *)zr_colorWithHexString:(NSString *)hexString{
    
    // stringByTrimmingCharactersInSet : 去掉空格
    // uppercaseString 转成 大写
    NSString * cString = [[hexString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] uppercaseString];
    
    if ([cString length] < 6) {  return [UIColor clearColor];}
    
    //判断前缀
    if ([cString hasPrefix:@"0X"]) { cString = [cString substringFromIndex:2];}
    if ([cString hasPrefix:@"#"]) { cString = [cString substringFromIndex:1];}
    if ([cString length] != 6) return [UIColor clearColor];
    
    NSRange range = NSMakeRange(0, 2);

    unsigned int r = 0,g = 0,b = 0;
    for (int i = 0; i < 3; i++) {
        
        NSString * rgbStr = [cString substringWithRange:range];
        range.location += 2;
      
        switch (i) {
            case 0: [[NSScanner scannerWithString:rgbStr] scanHexInt:&r];break;
            case 1: [[NSScanner scannerWithString:rgbStr] scanHexInt:&g];break;
            case 2: [[NSScanner scannerWithString:rgbStr] scanHexInt:&b];break;
                
            default:   break;
        }
    }
    
    return [UIColor colorWithRed:((float) r/255.0f) green:((float) g/255.0f) blue:((float) b/255.0f) alpha:1];
}

/** 16 进制 32位 转 UIcolor 例:[0xFF0000 -> 红色] */
+ (UIColor *)zr_colorWithHexNum:(uint32_t)hexNum{
    
    uint8_t r = (hexNum & 0xff0000) >> 16 ;
    uint8_t g = (hexNum & 0x00ff00) >> 8;
    uint8_t b = hexNum & 0x0000ff;
    
    return [UIColor colorWithRed:r green:g blue:b alpha:1];
}


#pragma mark - ----------------------- 纯色图片 -----------------------
/** 纯色图片 */
- (UIImage *)zr_colorImageWithWidth:(CGFloat)width height:(CGFloat)height cornerRadius: (CGFloat)cornerRadius{
    
    CGRect frame = CGRectMake(0, 0, width, height);
    
    UIGraphicsBeginImageContext(frame.size);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(ctx, [self CGColor]);

    [[UIBezierPath bezierPathWithRoundedRect:frame cornerRadius:cornerRadius] addClip];
    CGContextFillRect(ctx, frame);
 
    [[UIImage alloc] drawInRect:frame];
    UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
    
}


@end
